package form.ui.component.ScrollBar
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	import form.events.ScrollBarEvent;
	import form.ui.assets.Compiled;
	import form.ui.core.Button;
	
	public class Handle extends Button {
		private var _dragging:Boolean = false; 
		
		private var bounds:Rectangle;

		protected var scrollBar:ScrollBar;
		
		public function Handle(scrollBar:ScrollBar) 
		{
			super();
			if(labelField && contains(labelField)) 
			{
				removeChild(labelField);
			}
			this.scrollBar = scrollBar;
			
			this.mouseUp = new Compiled.ScrollBarHandleUp();
			this.mouseOver = new Compiled.ScrollBarHandleOver();
			this.mouseDown = new Compiled.ScrollBarHandleDown();

			this.enable();
		}
		
		public function get dragging():Boolean { return this._dragging; } 
		
		private function stopDragAction(e:Event):void
		{
			mouseUpAction();
		}
		
		private function onMouseMove(e:Event):void
		{
			if(bounds && _dragging)
			{
				var evt:ScrollBarEvent = new ScrollBarEvent(ScrollBarEvent.SCROLLED);
				evt.value = scrollBar.handleValue;
				this.dispatchEvent(evt);
			}
		}
		
		override public function mouseUpAction():void
		{	
			this.stopDrag();
		}
		
		override public function startDrag(lockCenter:Boolean=false, bounds:Rectangle=null):void
		{			
			this.bounds = bounds;
			super.startDrag(lockCenter, bounds);
			this._dragging = true;
			this.stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove, false, 0, true);
			this.stage.addEventListener(MouseEvent.MOUSE_UP, stopDragAction, false, 0, true);
		}
		
		override public function stopDrag():void
		{
			super.stopDrag();
			this._dragging = false; 
			this.stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			this.stage.removeEventListener(MouseEvent.MOUSE_UP, stopDragAction);			
			bounds = null;
		}
		
		override public function get width():Number
		{
			return this.mouseUp ? this.mouseUp.width : super.width;
		}
		override public function get height():Number
		{
			return this.mouseUp ? this.mouseUp.height : super.height;
		}
	}
}